<?php
/**
 * 备份类
 */
class model_backup {
	private $sql_text;
	private $tables;
	
	/**
	 * 导出SQL文本
	 * @param Array $tables
	 * @return String
	 */
	public function make_sql_text($tables = array(), $extra = '') {
		// 连接数据库
		$common_mysql = new common_mysql();
		
		// 初始化要导出的表
		if(empty($tables)) {
			$res = mysql_query("SHOW TABLES");
			while ($row = mysql_fetch_array($res)) {
				$tables[] = $row[0];
			}
		}
		
		// 初始化导出字符串
		$br = "\r\n";
		$hr = '-- -----------------'.$br;
		
		$sql_export = '';
		$sql_export .= '-- '.date('Y-m-d H:i:s').' - '.DB_NAME.$br.$br;
		$sql_export .= "SET NAMES UTF8;$br$br$hr";
		
		// 导出SQL语句
		foreach ($tables as $table) {
			$res = mysql_query("SHOW CREATE TABLE `$table`");     
			$sql = mysql_fetch_array($res);
			
			//CREATE TABLE 语句
			$sql_export .= $br.$sql['Create Table'].";$br$br";
			
			//INSERT INTO 语句
			$res = mysql_query("SELECT * FROM `$table` $extra");
			while ($row = mysql_fetch_assoc($res)) {
				$keys = array_keys($row);
				$keys = array_map('addslashes', $keys);
				$keys = join('`,`', $keys);   
				$keys = "`".$keys."`";  
				
				$values = array_values($row); 
				$values = array_map('addslashes', $values);  
				$values = join("','", $values); 
				$values = "'".$values."'";
				
				$sql_export .= "INSERT INTO `$table`($keys) VALUES ($values);".$br;
			}

			$sql_export .= $br.$hr;
		}
		
		$this->tables = $tables;
		$this->sql_text = $sql_export;
	}
	
	/**
	 * 获取SQL文本
	 */
	public function get_sql_text() {
		return $this->sql_text;
	}
	
	/**
	 * 发送备份邮件
     * todo 已废弃不用
	 */
	public function mail_sql_text($subject = '', $tables = array(), $extra = '') {
		$this->make_sql_text($tables, $extra);
		
		// 邮件相关
		$mail_subject = date('Y-m-d H:i').' Data Backup '.$subject;
		$mail_body = '[START]'.base64_encode($this->sql_text).'[END]';
		
		$smtp = new common_smtp('smtp.qq.com', 25, true, 'qroom@qq.com', 'cakephp1');
		
		// 获取要发送到的邮箱变量
		$model_var = new model_var();
		$backup_to_email = $model_var->get_all('backup_to_email');

		foreach ($backup_to_email as $row) {
			@$smtp->sendmail($row, 'qroom@qq.com', $mail_subject, $mail_body, 'TEXT');			
		}
		
		// 记录日志
		new model_logs($subject.' - '.round(strlen($mail_body) / 1024, 1).' Kb'.' - '.print_r($this->tables, 1));
	}
	
	/**
	 * 获取日志
	 */
	public function get_logs() {
		$model_logs = new model_logs();
		$res = $model_logs->find_all("action='backup_do'", 'create_time DESC', 100, 'create_time, body');
		foreach ($res as &$row) {
			$row['body'] = str_replace('all - ', '<span style="color:#f00;font-weight:bold;">All</span> - ', $row['body']);
		}
		return $res;
	}
}

?>
